package com.tianyu.inspection.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tianyu.inspection.common.Constants;
import com.tianyu.inspection.common.enums.FileTypeEnum;
import com.tianyu.inspection.common.enums.RoState;
import com.tianyu.inspection.common.enums.Role;
import com.tianyu.inspection.common.annotation.Permission;
import com.tianyu.inspection.common.component.PdfModel;
import com.tianyu.inspection.common.component.Validate;
import com.tianyu.inspection.entity.Danger;
import com.tianyu.inspection.entity.model.OperateMo;
import com.tianyu.inspection.entity.model.QueryMo;
import com.tianyu.inspection.entity.vo.Ro;
import com.tianyu.inspection.entity.vo.ServiceRo;
import com.tianyu.inspection.service.api.IDangerProcessService;
import com.tianyu.inspection.service.api.IDangerService;
import com.tianyu.inspection.service.api.IFlyTaskService;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**********************************
 * @Author YSW
 * @Description 施工单位接口
 * @Date 2021/1/15 - 18:12
 **********************************/

@RestController
@RequestMapping("/api/2.0/danger")
public class DangerController {

    @Resource
    private PdfModel pdfModel;

    @Resource
    private Validate validateModel;

    @Resource
    private IFlyTaskService flyTaskService;

    @Resource
    private IDangerService dangerService;

    @Resource
    private IDangerProcessService dangerProcessService;

    @GetMapping(value = "/list")
    @Permission(value = 4,tags = Constants.API_PATROL)
    public Ro<Object> getPageList(@RequestHeader("u-projectId") Integer projectId,
                                         @RequestHeader("u-uid") Integer userId,
                                         HttpServletRequest request){
        Integer roleId = (Integer) request.getAttribute("roleId");
        Ro<Object> ro = new Ro<>();
        QueryMo queryMo = QueryMo.getQueryMo(request);
        if (roleId.equals(Role.ROLE_SUPER_ADMIN.getValue())){
            queryMo.build(Danger.class,projectId);
            return ro.setContent(dangerService.searchListPage(queryMo));
        }else if (roleId.equals(Role.ROLE_COMPANY_ADMIN.getValue()) || roleId.equals(Role.ROLE_COMPANY_COMMON.getValue())){
            queryMo.build(Danger.class,projectId);
            return ro.setContent(dangerService.selectDangerDetailsList(queryMo));
        }else if (roleId.equals(Role.ROLE_PATROL.getValue())){
            QueryMo dangerQueryMo = new QueryMo();
            dangerQueryMo.putAll(queryMo);
            dangerQueryMo.put("inspectorId",userId);
            dangerQueryMo.build(Danger.class,projectId);
            ro.setResultEnum(RoState.SUCCESS);
            return ro.setContent(dangerService.selectPatrolDangerAndDangerTypeList2(dangerQueryMo));
        }
        return ro.setResultEnum(RoState.FAIL);
    }

    @GetMapping(value = "/list/details")
    @Permission(value = 4,tags = Constants.API_PATROL)
    public Ro<Object> getPageListDetails(@RequestHeader("u-projectId") Integer projectId,
                                  @RequestHeader("u-uid") Integer userId,
                                  HttpServletRequest request){
        Integer roleId = (Integer) request.getAttribute("roleId");
        Ro<Object> ro = new Ro<>();
        QueryMo queryMo = QueryMo.getQueryMo(request);
        if (roleId.equals(Role.ROLE_SUPER_ADMIN.getValue())){
            queryMo.build(Danger.class,projectId);
            return ro.setContent(dangerService.searchListPage(queryMo));
        }else if (roleId.equals(Role.ROLE_COMPANY_ADMIN.getValue()) || roleId.equals(Role.ROLE_COMPANY_COMMON.getValue())){
            queryMo.build(Danger.class,projectId);
            return ro.setContent(dangerService.selectDangerDeepDetailsList(queryMo));
        }else if (roleId.equals(Role.ROLE_PATROL.getValue())){
            QueryMo dangerQueryMo = new QueryMo();
            dangerQueryMo.putAll(queryMo);
            dangerQueryMo.put("inspectorId",userId);
            dangerQueryMo.build(Danger.class,projectId);
            ro.setResultEnum(RoState.SUCCESS);
            return ro.setContent(dangerService.selectPatrolDangerAndDangerTypeList2(dangerQueryMo));
        }
        return ro.setResultEnum(RoState.FAIL);
    }

    @GetMapping(value = "/{id}")
    @Permission(value = 3,tags = Constants.API_COMPANY)
    public Ro<Danger> getOne(@PathVariable Integer id, @RequestHeader("u-projectId") Integer projectId){
        Ro<Danger> ro = new Ro<>();
        if (Objects.isNull(id)){
            return ro.setResultEnum(RoState.PARAMS_MISS_ERROR);
        }
        QueryMo queryMo = new QueryMo();
        queryMo.put("id",id);
        queryMo.build(Danger.class,projectId);
        Danger danger = dangerService.selectOne(queryMo);
        if (Objects.isNull(danger)){
            ro.setMessage("未查询到数据");
        }else {
            ro.setContent(danger);
        }
        return ro;
    }


    @Permission(value = 3,tags = Constants.API_COMPANY)
    @GetMapping(value = "/details/{id}")
    public Ro<Danger> getDetailsOne(@PathVariable Integer id, @RequestHeader("u-projectId") Integer projectId) {
        QueryMo queryMo = new QueryMo();
        queryMo.put("id",id);
        queryMo.build(Danger.class,projectId);
        Danger danger = dangerService.selectOne(queryMo);
        if (Objects.isNull(danger)){
            return new Ro<Danger>(RoState.FAIL).setMessage("未查询到险情["+id+"]!");
        }
        return new Ro<Danger>().setContent(danger);
    }

    @Permission(value = 3,tags = Constants.API_COMPANY)
    @GetMapping(value = "/statistics")
    public Ro<ModelMap> dangerStatistics(@RequestHeader("u-projectId") Integer projectId,
                                         HttpServletRequest request) {
        QueryMo queryMo = QueryMo.getQueryMo(request);
        Ro<ModelMap> ro = new Ro<>(RoState.PARAMS_MISS_ERROR);
        if (request.getAttribute("roleId").equals(1)){
            if (Objects.isNull(queryMo.get("projectId"))){
                return ro.setMessage("缺少参数[projectId]");
            }
        }
        queryMo.build(Danger.class,projectId);
        ModelMap modelMap = dangerService.dangerStatistics(queryMo);
        if (Objects.nonNull(modelMap)){
            return ro.setContent(modelMap).setResultEnum(RoState.SUCCESS);
        }
        return ro;
    }

    @PostMapping(value = "/insert")
    @Permission(value = 3,tags = Constants.API_COMPANY)
    public Ro<Void> insert(@RequestBody OperateMo operateMo, @RequestHeader("u-projectId") Integer projectId,
                           @RequestHeader("u-uid") Integer userId){
        Ro<Void> ro = new Ro<>(RoState.PARAMS_MISS_ERROR);
        operateMo.createBuild(Danger.class,projectId);
        if (operateMo.getEntity().size() == 0){
            return ro.setResultEnum(RoState.FAIL).setMessage("无操作参数传入,请传参后重试");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        Danger danger = objectMapper.convertValue(operateMo.getEntity(), Danger.class);

        Integer dangerTypeId = danger.getDangerTypeId();
        Integer dangerLevelId = danger.getDangerLevelId();
        Integer flyTaskId = danger.getFlyTaskId();
        String labelImage = danger.getLabelImage();

        if (Objects.isNull(dangerTypeId)) {
            return ro.setMessage("请选择险情类型");
        }else {
            if (validateModel.dangerTypeIdValidate(dangerTypeId)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[dangerTypeId],值不存在");
            }
        }
        if (Objects.isNull(dangerLevelId)) {
            return ro.setMessage("请选择险情级别");
        }else {
            if (validateModel.dangerLevelIdValidate(dangerLevelId)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[dangerLevelId],值不存在");
            }
        }
        if (Objects.isNull(flyTaskId)) {
            ro.setMessage("缺少参数[flyTaskId]");
            return ro;
        }else {
            if (validateModel.flyTaskIdValidate(flyTaskId,projectId)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[flyTaskId],值不存在");
            }
        }
        if (Objects.isNull(labelImage)) {
            return ro.setMessage("请上传险情图片");
        }
        if (Objects.isNull(danger.getLng()) || Objects.isNull(danger.getLat())) {
            return ro.setMessage("请填写险情的经纬度信息");
        }
        //中国的纬度范围是北纬4°~53°
        if (danger.getLat() < 4 || danger.getLat() > 53) {
            return ro.setMessage("请填写正确维度度信息");
        }
        // 中国的经度范围是东经73°~135°,
        if (danger.getLng() < 73 || danger.getLng() > 135) {
            return ro.setMessage("请填写正确经度信息");
        }
        if (Objects.isNull(danger.getProjectId())) {
            return ro.setMessage(Role.ROLE_SUPER_ADMIN.getMessage()+"添加险情请传入参数[projectId]");
        }
        ServiceRo serviceRo = dangerService.insertDangerAndDangerProcess(operateMo,userId);
        if (!serviceRo.getResult()){
            ro.setResultEnum(RoState.FAIL).setMessage(serviceRo.getMessage());
        }else {
            ro.setResultEnum(RoState.SUCCESS);
        }
        return ro;
    }

    @PatchMapping(value = "/modify")
    @Permission(value = 2,tags = Constants.API_ADMIN)
    public Ro<Danger> modify(@RequestBody OperateMo operateMo, @RequestHeader("u-projectId") Integer projectId){
        Ro<Danger> ro = new Ro<>();
        final ServiceRo serviceRo0 = operateMo.updateBuild(Danger.class, projectId);
        if (!serviceRo0.getResult()){
            return ro.setResultEnum(RoState.FAIL).setMessage(serviceRo0.getMessage());
        }
        if (operateMo.getEntity().size()==0){
            return ro.setResultEnum(RoState.FAIL).setMessage("无操作参数传入,请传参后重试");
        }
        if (Objects.isNull(operateMo.get("id"))){
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少[id]字段,请传参后重试");
        }
        if (Objects.nonNull(operateMo.get("labelImage"))){
            if (validateModel.uploadImageValidate(FileTypeEnum.FILE_DANGER_IMG.getValue(), (String) operateMo.get("labelImage"))){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[labelImage],文件不存在或文件上传类别错误");
            }
        }
        ServiceRo serviceRo = dangerService.updateDangerAndDangerProcessUser(operateMo);
        if (!serviceRo.getResult()){
            ro.setResultEnum(RoState.FAIL).setMessage(serviceRo.getMessage());
        }
        return ro;
    }

    @DeleteMapping(value = "/admin/delete/{id}")
    @Permission(value = 1,tags = Constants.API_SUPER)
    public Ro<Danger> delete(@PathVariable Integer id, @RequestHeader("u-projectId") Integer projectId){
        Ro<Danger> ro = new Ro<>();
        QueryMo queryMo = new QueryMo();
        queryMo.put("id",id);
        queryMo.build(Danger.class,projectId);
        if (!dangerService.delete(queryMo)){
            ro.setResultEnum(RoState.FAIL).setMessage("无匹配ID,删除失败");
        }
        return ro;
    }

    @DeleteMapping(value = "/delete/logical/{id}")
    @Permission(value = 2,tags = Constants.API_ADMIN)
    public Ro<Danger>  logicallyDelete(@PathVariable Integer id,
                                       @RequestHeader("u-projectId") Integer projectId){
        Ro<Danger> ro = new Ro<>();
        QueryMo queryMo = new QueryMo();
        queryMo.put("id",id);
        queryMo.build(Danger.class,projectId);
        if (!dangerService.logicallyDelete(queryMo)){
            ro.setResultEnum(RoState.FAIL).setMessage("无匹配ID,删除失败");
        }
        return ro;
    }
}
